package com.happy.xiao.common.rabbitmq.db.service.impl;


import com.happy.xiao.common.rabbitmq.db.entity.MessageFailLog;
import com.happy.xiao.common.rabbitmq.bean.MessageSend;
import com.happy.xiao.common.rabbitmq.db.repository.MessageFailLogRepository;
import com.happy.xiao.common.rabbitmq.db.service.IMessageFailLogService;
import com.happy.xiao.common.utils.StringUtil;
import com.happy.xiao.common.utils.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class MessageFailLogServiceImpl implements IMessageFailLogService {

    @Autowired
    MessageFailLogRepository messageFailLogRepository;

    @Override
    public void add(MessageFailLog obj) {
        try {
            MessageFailLog save = messageFailLogRepository.save(obj);
            System.out.println(save.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param messageId
     * @param exchange
     * @param routingKey
     * @param message
     * @param expiration
     * @param failType   0 发送失败  1 消费失败
     */
    @Override
    public void createFailMessageInDB(String messageId,
                                      String exchange,
                                      String routingKey,
                                      String message,
                                      String expiration,
                                      int failType) {

        int delayTime = 0;

        // 这里是延时消息处理
        if (!StringUtils.isEmpty(expiration)) delayTime = Integer.parseInt(expiration);

        MessageSend insertData = new MessageSend(messageId, exchange, routingKey, message, delayTime);
        String messageStr = Util.ObjectToJson(insertData);
        MessageFailLog failLog = new MessageFailLog(messageStr, failType, StringUtil.time(), 0);
        add(failLog);
    }
}
